//
//  FaceKeyBoard.m
//  79环信
//
//  Created by 刘恒槟 on 15/8/4.
//  Copyright (c) 2015年 刘恒槟. All rights reserved.
//

#import "FaceKeyBoard.h"

@interface FaceKeyBoard ()

@property (nonatomic ,strong) UIScrollView * scrollView;

@end

@implementation FaceKeyBoard


-(instancetype)initWithFrame:(CGRect)frame{
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        [self faceItem];
        
        
    }
    return self;
}

-(void)faceItem{
    
    self.scrollView = [[UIScrollView alloc]initWithFrame:self.bounds];
    [self addSubview:self.scrollView];
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    self.scrollView.pagingEnabled = YES;
    
    [self addObserver:self forKeyPath:@"dataSource" options:NSKeyValueObservingOptionNew context:nil];
    
    
}

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    //按钮的数量
    NSInteger count = [self.dataSource numberOfFaceItemInFaceKeyBoard:self];

    //按钮的页数
    NSInteger page = count/32;
    if (count%32 != 0) {
        page += 1;
    }
    //scrollview的大小(contentSize)
    self.scrollView.contentSize = CGSizeMake(self.scrollView.frame.size.width*page, self.scrollView.frame.size.height);
    
    //将按钮循环贴在scrollview上，每页4行，每行8个
    for (int i = 0; i<count; i++)
    {
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.tag = i;
        [button addTarget:self action:@selector(tapButton:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.scrollView addSubview:button];
        //定位当前第几页
        NSInteger section = button.tag/32;
        //当前页的第多少个
        NSInteger s_index = button.tag%32;
        //当前列
        NSInteger s_lie = s_index%8;
        //当前行
        NSInteger s_hang = s_index/8;
        
        NSInteger w = self.scrollView.frame.size.width;
        CGFloat a = w/8;
        //当前按钮的坐标
        CGFloat x = w * section +s_lie * (w/8);
        CGFloat y = s_hang * (w/8);
        
        CGRect frame = CGRectMake(x, y, a, a);
        
        button.frame = frame;
        
        
        //将图片取出来设置为button的图片
        UIImage * image = [self.dataSource FaceKeyboard:self FaceItemImageAtIndex:i];
        [button setImage:image forState:UIControlStateNormal];
        
    }
}

-(void)tapButton:(UIButton *)button{
    
    if ([self.delegate respondsToSelector:@selector(FaceKeyBoard:didTapFaceItemIndex:)]) {
        
        [self.delegate FaceKeyBoard:self didTapFaceItemIndex:button.tag];
    }
}

-(void)dealloc{
    
    [self removeObserver:self forKeyPath:@"dataSource"];
    
}

@end
